//
//  Follow_ViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 15/6/23.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "Follow_ViewController.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "followInfor.h"
#import "focus_TableViewCell.h"
#import "My_ViewController.h"
#import "userInformationViewController.h"
@interface Follow_ViewController ()<UITableViewDelegate, UITableViewDataSource, MJRefreshBaseViewDelegate>
{
    int page;
    int pages;
    UIImageView *NOFollow;
    MJRefreshSystemHeaderView *header;
    MJRefreshFooterView *footer;
}
@property (strong, nonatomic) UITableView *followTableview;
@property (strong, nonatomic) NSMutableArray *followArray;
@end

@implementation Follow_ViewController
-(instancetype)initWithSelfUid:(NSString *)uid
{
    self = [super init];
    if (self) {
        self.selfuid = uid;
        self.followArray = [[NSMutableArray alloc] init];
        self.hidesBottomBarWhenPushed = YES;
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        [back setFrame:CGRectMake(0, 0, 30, 30)];
        [back setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
        [back addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:back];
        self.navigationItem.leftBarButtonItem = backItem;
        page = 1;
        [self requestDataWithUid:uid refreshing:nil page:page];
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [header beginRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"关注";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    // Do any additional setup after loading the view.
    
}

- (void)createTableview
{
    self.followTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    _followTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _followTableview.dataSource = self;
    _followTableview.delegate = self;
    _followTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _followTableview.separatorColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
    [self.view addSubview:_followTableview];
    header = [MJRefreshSystemHeaderView header];
    header.scrollView = _followTableview;
    header.delegate = self;
    footer = [MJRefreshFooterView footer];
    footer.scrollView = _followTableview;
    footer.delegate = self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _followArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (self.view.height) / 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [NSString stringWithFormat:@"foucsCell"];
    // 检查表视图中是否存在闲置的单元格
    focus_TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[focus_TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    if (_followArray.count > 0) {
        cell.focustabViewModel = _followArray[indexPath.row];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    followInfor *model = _followArray[indexPath.row];
//    NSLog(@"id------->%@", model.id);
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] isEqualToString:model.id]) {
        if (self.tabBarController.selectedIndex == 4) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"stopAudioPlayer" object:nil];
            [self.tabBarController setSelectedIndex:4];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    } else {
        userInformationViewController *userinformation = [[userInformationViewController alloc] initWithSelfUid:model.id];
        [self.navigationController pushViewController:userinformation animated:YES];
    }
    
}
#pragma mark -
#pragma mark 网络请求
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshSystemHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        footer.hidden = NO;
        [_followArray removeAllObjects];
        [self requestDataWithUid:_selfuid refreshing:refreshView page:page];
    }else {
        if (pages == 1 && page == pages) {
            footer.hidden = YES;
        } else {
            page++;
            [self requestDataWithUid:_selfuid refreshing:refreshView page:page];
        }

    }
}
- (void)requestDataWithUid:(NSString *)uid refreshing:(MJRefreshBaseView *)refresh page:(int)pag
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *userheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
        [manager.requestSerializer setValue:userheader forHTTPHeaderField:@"authorization"];
    NSString *fansString=[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/following?p=%d",uid,pag];
    [manager GET:fansString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [responseObject valueForKey:@"data"];
        for (NSDictionary *dict in dic) {
            followInfor *followModel = [[followInfor alloc] init];
            [followModel setValuesForKeysWithDictionary:dict];
            [_followArray addObject:followModel];
        }
        if (dic.count == 0) {
            footer.hidden = YES;
        }
        if (_followArray.count > 0) {
            if (_followTableview == nil) {
                [self createTableview];
            } else {
                [_followTableview reloadData];
            }
        } else {
            NOFollow = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.6)];
            NOFollow.image = [UIImage imageNamed:@"noFoucs"];
            [self.view addSubview:NOFollow];
        }
        [refresh performSelector:@selector(endRefreshing) withObject:nil afterDelay:0];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}
- (void)backTo
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
